<script setup lang="ts">
import LEchart from '@/pagesReport/lime-echart/components/l-echart/l-echart.vue'
import { onMounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { useReportStore } from '@/stores'
const sleepStageChart = ref()
const reportStore = useReportStore()
const lowSleepPercent = ref(0)
const rpercent = ref(0)
const deepSleepPercent = ref(0)
const sleepStageoption = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {d}%',
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    itemHeight: 5,
    itemWidth: 5,
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      legend: {
        left: 'left',
      },
      data: [
        {
          value: lowSleepPercent.value,
          name: '浅睡',
          itemStyle: { color: '#82eaf7' },
        },
        {
          value: rpercent.value,
          name: 'R期',
          itemStyle: { color: '#bde358' },
        },
        {
          value: deepSleepPercent.value,
          name: '深睡',
          itemStyle: { color: '#65b4f8' },
        },
      ],
    },
  ],
})
onMounted(async () => {
  if (!reportStore.report) return
  lowSleepPercent.value = +reportStore?.report?.sleepStagesInfo.lowSleepPercent.replace('%', '')
  rpercent.value = +reportStore?.report?.sleepStagesInfo.rpercent.replace('%', '')
  deepSleepPercent.value = +reportStore?.report?.sleepStagesInfo.deepSleepPercent.replace('%', '')
  sleepStageoption.value.series[0].data[0].value = lowSleepPercent.value
  sleepStageoption.value.series[0].data[1].value = rpercent.value
  sleepStageoption.value.series[0].data[2].value = deepSleepPercent.value
  const sleepStagechart = await sleepStageChart.value.init(echarts)
  sleepStagechart.setOption(sleepStageoption.value)
})
watch(
  () => reportStore.report,
  async (newReport) => {
    if (newReport) {
      lowSleepPercent.value = +newReport.sleepStagesInfo.lowSleepPercent.replace('%', '')
      rpercent.value = +newReport.sleepStagesInfo.rpercent.replace('%', '')
      deepSleepPercent.value = +newReport.sleepStagesInfo.deepSleepPercent.replace('%', '')
      sleepStageoption.value.series[0].data[0].value = lowSleepPercent.value
      sleepStageoption.value.series[0].data[1].value = rpercent.value
      sleepStageoption.value.series[0].data[2].value = deepSleepPercent.value
      const sleepStagechart = await sleepStageChart.value.init(echarts)
      sleepStagechart.setOption(sleepStageoption.value)
    }
  },
)
</script>
<template>
  <view class="chart">
    <LEchart ref="sleepStageChart"></LEchart>
  </view>
</template>
